<script>
export default {
  onLaunch: function() {
    console.log('App Launch')
    this.initApp()
  },
  onShow: function() {
    console.log('App Show')
  },
  onHide: function() {
    console.log('App Hide')
  },
  methods: {
    async initApp() {
      try {
        // 检查登录状态
        const isLogged = await this.checkLoginStatus()
        
        if (!isLogged) {
          // 未登录，执行微信登录
          await this.wechatLogin()
        }
        
        // 登录成功，触发全局事件
        uni.$emit('appInitComplete', { success: true })
      } catch (error) {
        console.error('应用初始化失败:', error)
        uni.$emit('appInitComplete', { success: false, error })
        
        // 显示错误提示
        uni.showToast({
          title: '应用初始化失败，请重启',
          icon: 'none',
          duration: 3000
        })
      }
    },
    
    async checkLoginStatus() {
      try {
        // 检查本地存储的token和用户信息
        const token = uni.getStorageSync('auth_token')
        const userInfo = uni.getStorageSync('user_info')
        const tokenExpire = uni.getStorageSync('token_expire')
        
        // 检查token是否存在且未过期
        if (token && userInfo && tokenExpire) {
          const now = Date.now()
          if (now < tokenExpire) {
            console.log('用户已登录，token有效')
            return true
          } else {
            console.log('token已过期，需要重新登录')
            // 清除过期token
            uni.removeStorageSync('auth_token')
            uni.removeStorageSync('token_expire')
          }
        }
        
        return false
      } catch (error) {
        console.error('检查登录状态失败:', error)
        return false
      }
    },
    
    async wechatLogin() {
      return new Promise((resolve, reject) => {
        console.log('开始微信登录流程')
        
        // 第一步：获取微信登录code
        uni.login({
          provider: 'weixin',
          success: async (loginRes) => {
            if (loginRes.code) {
              console.log('获取到微信code:', loginRes.code)
              
              try {
                // 第二步：将code发送到后端服务器
                const loginResult = await this.sendCodeToServer(loginRes.code)
                
                // 第三步：保存登录状态
                uni.setStorageSync('auth_token', loginResult.token)
                uni.setStorageSync('user_info', loginResult.userInfo)
                // 设置token过期时间（假设后端返回的expires_in是秒数）
                const expireTime = Date.now() + (loginResult.expires_in || 7200) * 1000
                uni.setStorageSync('token_expire', expireTime)
                
                console.log('微信登录成功，用户信息:', loginResult.userInfo)
                resolve(loginResult)
              } catch (err) {
                console.error('登录请求失败:', err)
                reject(err)
              }
            } else {
              const error = new Error('获取微信登录code失败')
              console.error(error.message)
              reject(error)
            }
          },
          fail: (err) => {
            console.error('调用微信登录接口失败:', err)
            reject(err)
          }
        })
      })
    },
    
    async sendCodeToServer(code) {
      return new Promise((resolve, reject) => {
        uni.request({
          // url: 'http://121.5.38.73:9999/api/auth/wechat-login',
		  url: 'http://127.0.0.1:9999/api/auth/wechat-login',
          method: 'POST',
          data: {
            code: code
          },
          header: {
            'Content-Type': 'application/json'
          },
          success: (res) => {
            if (res.statusCode === 200 && res.data.success) {
              resolve(res.data.data)
            } else {
              let errorMsg = '登录请求失败'
              if (res.data && res.data.message) {
                errorMsg = res.data.message
              }
              reject(new Error(errorMsg))
            }
          },
          fail: (err) => {
            reject(err)
          }
        })
      })
    }
  }
}
</script>

<style>
/* 全局样式 */
page {
  background-color: #f5f5f5;
  height: 100%;
  font-size: 14px;
}

.container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

/* 通用按钮样式 */
.btn-primary {
  background-color: #2979FF;
  color: white;
  border-radius: 4px;
  padding: 8px 16px;
  text-align: center;
}

.btn-green {
  background-color: #07C160;
  color: white;
  border-radius: 4px;
  padding: 8px 16px;
  text-align: center;
}

/* 输入框样式 */
.input-field {
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  padding: 10px;
  background-color: white;
}

/* 加载动画 */
.loading {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #2979FF;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style>